﻿using System;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using MyMeetup.ViewModels;

namespace MyMeetup
{
    public partial class EventPage : PhoneApplicationPage
    {
        private Event _event;
        protected int guestCount = 0;
        public string myrsvp2;
        private bool networkError = false;

        private EventPageViewModel _viewModel;

        public EventPage()
        {
            InitializeComponent();
            Loaded += PageLoaded;
            _viewModel = DataContext as EventPageViewModel;
        }


        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (_event == null && State.ContainsKey("CurrentEvent"))
                _event = State["CurrentEvent"] as Event;

        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            State["CurrentEvent"] = _event;
        }


        private void PageLoaded(object sender, RoutedEventArgs e)
        {
            //if (_event == null) NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));

            if (_viewModel.Model.GetDate() != DateTime.MinValue && _viewModel.Model.GetDate().Date < DateTime.Now.Date)
            {
                eventPivot.Items.Remove(rsvpView);
            }
            else
            {
                eventPivot.Items.Remove(rateView);
            }


            //if (_event.myrsvp == "none") 
                //rsvp.Visibility = Visibility.Visible;

            if (_viewModel.Model.venue == null)
                mapLink.Visibility = Visibility.Collapsed;
            else
                mapLink.NavigateUri = new Uri("/MapPage.xaml?lon=" + _viewModel.Model.venue.lon + "&lat=" + _viewModel.Model.venue.lat + "&title=" + _viewModel.Model.venue.name,
                                        UriKind.Relative);

        }



        private void ImageClick(object sender, RoutedEventArgs e)
        {
            var selectedImage = ((Button)sender).DataContext as Photo;
            NavigationService.Navigate(new Uri("/PhotoPage.xaml?&url=" + selectedImage.photo_link, UriKind.Relative));

        }



         private void eventPivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
         {
             switch (((PivotItem)eventPivot.SelectedItem).Name)
             {
                 case "eventPhotos":
                     DisplayPhotoMenu();
                     break;
                 case "rateView":
                     DisplayRatingMenu();
                     break;
                 default:
                     ClearAppBar();
                     break;
             }
         }

        private void ClearAppBar()
        {
            ApplicationBar.Buttons.Clear();
            ApplicationBar.MenuItems.Clear();
            ApplicationBar.IsVisible = false;
        }

        private void DisplayPhotoMenu()
        {
            ClearAppBar();
            var ib1 = new ApplicationBarIconButton(new Uri("/Images/appbar.add.rest.png", UriKind.Relative)) { Text = "add" };
            ib1.Click += AddPhoto;
            ApplicationBar.Buttons.Add(ib1);
            ApplicationBar.IsVisible = true;
        }
        
        private void DisplayRatingMenu()
        {
            ClearAppBar();
            var menuItem = new ApplicationBarMenuItem("rate it");
            menuItem.Click += RateEvent;
            ApplicationBar.MenuItems.Add(menuItem);
            ApplicationBar.IsVisible = true;
        }


        private void RateEvent(object sender, EventArgs e)
        {
            if(LicenseHelper.IsTrial())
            {
                NavigationService.Navigate(new Uri("/BuyNow.xaml", UriKind.Relative));
            }

            NavigationService.Navigate(new Uri(string.Format("/RateItPage.xaml?eventId={0}&title={1}", _viewModel.Model.id, _viewModel.Model.name), UriKind.Relative));
        }
        
         private void AddPhoto(object sender, EventArgs e)
         {
             if (LicenseHelper.IsTrial())
             {
                 NavigationService.Navigate(new Uri("/BuyNow.xaml", UriKind.Relative));
             }
             else
             {
                 if (networkError)
                 {
                     MessageBox.Show("A network error has been detected. Please try again later.", "Network Error",
                                     MessageBoxButton.OK);
                     return;
                 }
                 var task = new PhotoChooserTask();
                 task.Completed += ImageObtained;
                 task.Show();
             }
         }

         void ImageObtained(object sender, PhotoResult e)
         {
             if (e.TaskResult == TaskResult.OK)
             {
                 if (_viewModel.PostPhotoCommand.CanExecute("")) _viewModel.PostPhotoCommand.Execute(e);
             }
         }

    }
}